//
//  COGiftPresentController.swift
//  CocoProject
//
//  Created by Vill on 2023/11/14.
//

import UIKit

typealias rechargeblock = ()->Void
typealias giftSendblock = (_ model:COGiftModel)->Void

class COGiftPresentController: SFPresentBottomViewController,SFPresentBottomViewControllerProtocol {
    
    var giftRecharge:rechargeblock?
    var giftSend:giftSendblock?
    
    // 控制器高度
    var controllerHeight: CGFloat = PTW(360) + KSafeBottomMargin
    var chooseGiftModel = COGiftModel()
    
    // 礼物数组
    var gifts : [COGiftModel]!{
        didSet {
            setContent()
        }
    }
    
    lazy var containerView: UIView = {
        let top = UIView()
        top.backgroundColor = UIColor.colorWithHex("#D2D3D5")
        return top
    }()
    
    // 金币图片
    lazy var coinsImg:UIImageView = {
        let coin = UIImageView()
        coin.image = KImaged("coco_mine_star")
        return coin
    }()
    
    // 金币数
    lazy var coinsLbl:UILabel = {
        let coin = UILabel()
        coin.textColor = UIColor.colorWithHex("#8835FF")
        coin.font = UIFont.pingfangFont(ofSize: PTW(18), weight: .medium)
        let model = COUserInfoManager.shared.curUser
        coin.text = "\(model?.userResponse.balance ?? 0)"
        return coin
    }()
    
    // 充值
    lazy var rechargeBtn: UIButton = {
        let recharge = UIButton()
        recharge.setTitle("Recharge>", for: .normal)
        recharge.titleLabel?.font =  UIFont.pingfangFont(ofSize: PTW(15), weight: .medium)
        recharge.setTitleColor(UIColor.colorWithHex("#FF4D95"), for: .normal)
        recharge.addTarget(self, action: #selector(recharAction), for: .touchUpInside)
        return recharge
    }()
    
    lazy var sentBtn: UIButton = {
        let sent = UIButton()
        sent.setTitle("Sent", for: .normal)
        sent.titleLabel?.font =  UIFont.pingfangFont(ofSize:PTW(16), weight: .medium)
        sent.setTitleColor(.white, for: .normal)
        sent.layer.cornerRadius = PTW(17.5)
        sent.layer.masksToBounds = true
        sent.addTarget(self, action: #selector(sentAction), for: .touchUpInside)
        return sent
    }()
    
    @objc func recharAction(){
        self.dissMiss()
        if self.giftRecharge != nil{
            self.giftRecharge!()
        }
    }
    
    @objc func sentAction(){
        if self.chooseGiftModel.name.count > 0 {
            self.dissMiss()
            if self.giftSend != nil {
                self.giftSend!(self.chooseGiftModel)
            }
        }else{
            UIToolHelper.makeToast("Please choose a gift!")
        }
    }

    lazy var collectionView: UICollectionView = {
        let config = FlowLayoutConfig()
        config.columnCountOfRow = 4 // 一行有多少列
        config.rowCountOfPage = 2   // 一页有多少行
        config.contentInsets = UIEdgeInsets(top: PTW(5), left: PTW(5), bottom: PTW(5), right: PTW(5))
        config.columnSpacing = PTW(5)    // 列间距
        config.lineSpacing = PTW(5)      // 行间距
        let layout = PagingFlowLayout(config: config)
        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout:layout)
        collectionView.isPagingEnabled = true
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.backgroundColor = .clear
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.register(COGiftCollectionListCell.self, forCellWithReuseIdentifier: "COGiftCollectionListCell")
        return collectionView
    }()
    
    lazy var pageControl:SnakePageControl = {
        let page = SnakePageControl()
        page.indicatorPadding = PTW(8)
        page.indicatorRadius = PTW(4)
        page.activeTint =  UIColor.colorWithHex("#FF3DE1")
        page.inactiveTint = UIColor.colorWithHex("#FFFFFF")
        return page
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(containerView)
        containerView.addSubview(pageControl)
        containerView.addSubview(collectionView)
        containerView.addSubview(coinsImg)
        containerView.addSubview(coinsLbl)
        containerView.addSubview(rechargeBtn)
        containerView.addSubview(sentBtn)
        
        containerView.snp.makeConstraints { make in
            make.leading.trailing.bottom.equalToSuperview()
            make.height.equalTo(controllerHeight)
        }
        pageControl.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(PTW(25))
        }
        collectionView.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview()
            make.height.equalTo(PTW(250))
            make.top.equalToSuperview().offset(PTW(60))
        }
        coinsImg.snp.makeConstraints { make in
            make.size.equalTo(PTW(25))
            make.leading.equalToSuperview().offset(PTW(15))
            make.top.equalTo(collectionView.snp.bottom).offset(PTW(15))
        }
        coinsLbl.snp.makeConstraints { make in
            make.leading.equalTo(coinsImg.snp.trailing).offset(PTW(6))
            make.centerY.equalTo(coinsImg)
        }
        rechargeBtn.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: PTW(85), height: PTW(40)))
            make.centerY.equalTo(pageControl)
            make.trailing.equalToSuperview().offset(-PTW(12))
        }
        sentBtn.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: PTW(88), height: PTW(35)))
            make.trailing.equalToSuperview().offset(-PTW(10))
            make.centerY.equalTo(coinsImg)
        }
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        self.containerView.clipsCorners(corners: [.topLeft,.topRight], radius: PTW(20))
        DispatchQueue.main.async {
            self.sentBtn.backgroundColor = UIColor.gradientFromColor(colors: [UIColor.colorWithHex("#7038FF").cgColor,UIColor.colorWithHex("#FF3DE1").cgColor], direction: .Horizontal, range: self.sentBtn.bounds.width)
        }
    }
    
    // 布局
    func setContent(){
        pageControl.pageCount = self.gifts.count/8 + 1
        collectionView.reloadData()
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let page = scrollView.contentOffset.x / SCREENWIDTH
        let progressInPage = scrollView.contentOffset.x - (page * SCREENWIDTH)
        let progress = CGFloat(page) + progressInPage
        pageControl.progress = progress
    }
    
    func dissMiss() {
        self.presentingViewController?.dismiss(animated: true, completion: nil)
    }
}

extension COGiftPresentController:UICollectionViewDelegate,UICollectionViewDataSource{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return gifts.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "COGiftCollectionListCell", for: indexPath) as! COGiftCollectionListCell
        cell.giftModel = self.gifts[indexPath.item]
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let giftModel = self.gifts[indexPath.item]
        self.chooseGiftModel = giftModel
    }
}
